import React, {Component} from 'react';
import { DownOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons';
// import styles from './style.css'
import { Button, Dropdown, Input, Menu, message, Table } from "antd";
// import {resetPassword} from "../../services/security";
// import {queryRelationMappingStatistic} from "@/services/ontology";
import {allusers, resetPassword, userChange} from "@/services/login";

let temp = [];
const ADMIN = "ADMIN";
const USER = "USER";
const forge = require('node-forge');

class UserManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userList: [],
      filterDropdownVisible: false,
      pagination: {
        position: 'bottom',
        total: 0,
        showTotal: (total) => {
          return `总共 ${total} 条`;
        },
        pageSize: 10,
        pageNum:1,
      },
      searchText: '',
      filtered: false,
    }

  }

  /**
   * 搜索所有用户
   */
  fetchAllUsers() {
    const {pagination} = this.state
    const query = {
      pageSize: 10,
      pageNum: pagination.pageNum,
      data:{
        username:this.state.searchText
      }
    }
    allusers(query).then(res => {
      const pagination=this.state.pagination
      pagination.total = res.data.total
      this.setState({
        userList: res.data.list.filter(item =>{
          return item.username !== 'root'
        }),pagination
      })
      temp = res.data.list.filter(item =>{
        return item.username !== 'root'
      });
    })
  }

  componentWillMount() {
    this.fetchAllUsers()
  }

  menu(record) {
    return <Menu>
      <Menu.Item>
        <a href="javascript:void(0);" onClick={this.modifyUser.bind(this, record, ADMIN)}>高级用户</a>
      </Menu.Item>
      <Menu.Item>
        <a href="javascript:void(0);;" onClick={this.modifyUser.bind(this, record, USER)}>普通用户</a>
      </Menu.Item>
    </Menu>
  }


  /**
   *   获取输入框值
   */
  onInputChange = (e) => {
    this.setState({searchText: e.target.value});
  };
  /**
   *   根据现有数据搜索，不会再调后台
   */
  onSearch = () => {
    const {searchText,pagination} = this.state;
    const reg = new RegExp(searchText, 'gi');
    let currentPagination = this.state.pagination;
    pagination.pageNum = 1;
    pagination.current = 1
    this.setState({pagination},_=>{
      this.fetchAllUsers()
    })
    // this.setState({
    //   filterDropdownVisible: false,
    //   filtered: !!searchText,
    //   userList: temp.map((record) => {
    //     const match = record.username.match(reg);
    //     if (!match) {
    //       return null;
    //     }
    //     currentPagination.total++;
    //     return {
    //       ...record,
    //       userName:record.username,
    //       username: (
    //         <span>
    //           {record.username.split(
    //             new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i')).map(
    //             (text, i) => (
    //               text.toLowerCase() === searchText.toLowerCase() ?
    //                 <span key={i} className="highlight" style={{color: '#29CCB1'}}>{text}</span> : text // eslint-disable-line
    //             ))}
    //         </span>
    //       ),
    //     };
    //   }).filter(record => !!record),
    //   pagination: currentPagination
    //
    // });
  };

  modifyUser(record, role) {
    const data = {
      userId: record.userId,
      roleId: role === ADMIN ? 2 : 3
    }
    userChange(data).then(res => {
      if (res.retCode === "0") {
        message.success("修改成功")
      } else {
        message.error("修改失败")
      }
      this.fetchAllUsers();
    })
  }

  resetPassword(record) {
    const username = record.userName ? record.userName : record.username
    resetPassword(record.userId,username).then(res => {
      if (res.retCode === "0") {
        message.success(username + '密码重置成功，默认密码是123456')
      } else {
        message.error(username + '密码修改失败')
      }
    })
  }
  userManageHandleTableChange(pagination) {
    const pager = { ...this.state.pagination };
    pager.pageNum = pagination.current;
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    },_=>{
      this.fetchAllUsers()
    });
  }

  render() {

    const columns_users = [
      {
        title: '用户名',
        width: '200px',
        dataIndex: 'username',
        key: 'username',
        filterDropdown: (
          <div>
            <Input
              ref={ele => this.searchInput = ele}
              placeholder="请输入用户名"
              value={this.state.searchText}
              onChange={this.onInputChange}
              onPressEnter={this.onSearch}
            />
          </div>
        ),
        filterIcon: <SearchOutlined
          style={{
            fontSize: 18,
            color: this.state.filtered ? '#108ee9' : '#aaa'
          }} />,
        filterDropdownVisible: this.state.filterDropdownVisible,
        onFilterDropdownVisibleChange: (visible) => {
          this.setState({
            filterDropdownVisible: visible,
          }, () => this.searchInput && this.searchInput.focus());
        },
      }, {
        title: "用户权限",
        key: 'kgdRole',
        width: "200px",
        render: (record) => {
          let element = <span></span>;
          if (record.role){
            if (record.role.description){
              const description = record.role.description
              element = <span>{description}<DownOutlined /></span>
            }
          }else {
            element = <span>未设置<DownOutlined /></span>
          }
          return <Dropdown overlay={this.menu(record)}>{element}</Dropdown>;
        }
      }
      , {
        title: "重置密码",
        width: "150px",
        key:'reset',
        render: (record) => {
          return <SyncOutlined onClick={this.resetPassword.bind(this, record)} />;
        }
      }
    ];

    return <div style={{border: 0}}>
      <Table columns={columns_users} rowKey={record => record.id}
             pagination={this.state.pagination}
             dataSource={this.state.userList} scroll={{y: "550px"}}
             onChange={this.userManageHandleTableChange.bind(this)}
      />
    </div>
  }

}

export default UserManage
